package team.bluepen.order.web.servlet.user;

import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.Constant;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.database.mysql.UserRepository;
import team.bluepen.order.data.entity.Role;
import team.bluepen.order.data.entity.User;
import team.bluepen.order.util.StringUtil;
import team.bluepen.order.web.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author RollW
 */
@WebServlet(name = "UserGetServlet", urlPatterns = "/api/user/get")
public class UserGetServlet extends BaseServlet {
    public static final String USERNAME_PARAM = "username";

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter(USERNAME_PARAM);
        setJsonHeader(resp);
        User user = (User) req.getSession().getAttribute(Constant.SESSION_USER);
        if (user == null || user.getRole() != Role.ADMIN) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_ILLEGAL_ACCESS,
                    "Non-administrator users are not allowed to get users data.")
                    .toCodePack());
            return;
        }
        List<User> userList;
        UserRepository repository = new UserRepository();
        if (StringUtil.isEmpty(username)) {
            userList = repository.getUserDao().get();
        } else {
            userList = Collections.singletonList(repository.getUserDao().get(username));
        }
        writeJson(resp, userList);
    }
}
